package com.cjhedu.web.utils;

import com.cjhedu.web.config.MyJwtPeoperties;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author 陈佳豪
 * @version 1.0
 * 生成和解析令牌的工具类
 */
@Component
public class MyJwtUtils {
    @Autowired
    private MyJwtPeoperties myJwtPeoperties;
    //生成令牌
    public String createJwt(Map<String,Object> map){
        String s = Jwts.builder()
                .setClaims(map)
                .signWith(SignatureAlgorithm.valueOf(myJwtPeoperties.getSignType()),myJwtPeoperties.getKey())
                .setExpiration(new Date(System.currentTimeMillis() + myJwtPeoperties.getMiss()))
                .compact();
        return s;
    }

    //解析令牌
    public Map<String,Object> jieXiJwt(String jwt){
        if (jwt == null || jwt.trim().isEmpty()) {
            throw new IllegalArgumentException("Token 不能为空");
        }
        Claims s = null;
        try {
            s = Jwts.parser()
                    .setSigningKey(myJwtPeoperties.getKey())
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            e.printStackTrace();
        }
        return s;
    }

}
